package com.wut.clock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wut.clock.common.constant.MessageConstant;
import com.wut.clock.common.service.RedisService;
import com.wut.clock.common.util.RedisKeyUtil;
import com.wut.clock.entity.Favorite;
import com.wut.clock.entity.Message;
import com.wut.clock.entity.SysUser;
import com.wut.clock.event.EventProducer;
import com.wut.clock.mapper.ArticleMapper;
import com.wut.clock.mapper.FavoriteMapper;
import com.wut.clock.mapper.SysUserMapper;
import com.wut.clock.mongo.dto.CollectionParams;
import com.wut.clock.mongo.repository.CollectionRepository;
import com.wut.clock.service.ICollectionService;
import com.wut.clock.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author ZYH
 * @unit D9Lab
 * @description 收藏接口实现类
 * @date 2022/6/11 10:55
 */
@Service
@RequiredArgsConstructor
public class CollectionServiceImpl implements ICollectionService {

    private final CollectionRepository collectionRepository;

    private final FavoriteMapper favoriteMapper;

    private final SysUserMapper userMapper;

    private final EventProducer eventProducer;

    private final ArticleMapper articleMapper;

    private final RedisTemplate redisTemplate;


    @Override
    public int addFavorite(Favorite favorite) {
        favorite.setUserId(ShiroUtil.getUserId());
        return favoriteMapper.insert(favorite);
    }

    @Override
    public int updateFavorite(Favorite favorite) {
        return favoriteMapper.updateById(favorite);
    }


    @Transactional
    @Override
    public int deleteFavorite(Integer favoriteId) {
        Integer userId = ShiroUtil.getUserId();
        int res = favoriteMapper.deleteById(favoriteId);
        Pageable pageable = PageRequest.of(0,10000);
        // 删除文件夹下面的文章收藏
        Page<CollectionParams> collectionParams =
                collectionRepository.findByUserIdAndFavoriteIdOrderByCreateTimeDesc(userId, favoriteId, pageable);
        if(collectionParams.getTotalElements() > 0)
            return collectionRepository.deleteAllByUserIdAndFavoriteId(userId,favoriteId);
        return res;
    }

    @Override
    public List<Favorite> getFavoriteList() {
        return favoriteMapper.selectList(new QueryWrapper<Favorite>().eq("user_id",ShiroUtil.getUserId()));
    }

    @Override
    public int addCollection(CollectionParams collectionParams) {
        int res = 0;
        SysUser user = userMapper.selectById(ShiroUtil.getUserId());
        collectionParams.setUserId(user.getId());
        collectionParams.setNickname(user.getNickname());
        collectionParams.setAvatar(user.getAvatar());
        collectionParams.setCreateTime(new Date());
        Integer articleId = collectionParams.getArticleId();
        CollectionParams params = collectionRepository.findByUserIdAndArticleId(user.getId(), articleId);
        if(params == null){
            collectionRepository.save(collectionParams);
            // 添加收藏事件
            Message message = new Message();
            Integer userId = articleMapper.selectById(articleId).getUserId();
            message.setUserId(userId);
            message.setFromUserId(ShiroUtil.getUserId());
            message.setTargetId(articleId);
            message.setTargetType(MessageConstant.TargetType.ARTICLE.getCode());
            message.setType(MessageConstant.Type.COLLECTION.getCode());
            eventProducer.fireCollectionEvent(message);
            String redisKey = RedisKeyUtil.getArticleScore();
            redisTemplate.opsForSet().add(redisKey,articleId);
            res++;
        }
        return res;
    }

    @Override
    public int deleteCollection(Integer articleId) {
        String redisKey = RedisKeyUtil.getArticleScore();
        redisTemplate.opsForSet().add(redisKey,articleId);
        return collectionRepository.deleteByUserIdAndArticleId(ShiroUtil.getUserId(),articleId);
    }

    @Override
    public Page<CollectionParams> getCollectionList(Integer pageNum, Integer pageSize, Integer favoriteId) {
        Integer userId = ShiroUtil.getUserId();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        return collectionRepository.findByUserIdAndFavoriteIdOrderByCreateTimeDesc(userId,favoriteId,pageable);
    }
}
